package com.eneat.smartrule.controller;

import com.eneat.smartrule.dto.request.RuleExecuteRequest;
import com.eneat.smartrule.dto.request.RuleReq;
import com.eneat.smartrule.dto.response.PageResponse;
import com.eneat.smartrule.dto.response.RuleRes;
import com.eneat.smartrule.model.Rule;
import com.eneat.smartrule.service.RuleService;
import com.eneat.smartrule.restAPI.AbstractController;
import com.eneat.smartrule.restAPI.HttpResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(path = "/v1/rule")
@Tag(name = "规则引擎相关接口")
@Slf4j
@CrossOrigin
public class RuleController extends AbstractController {

    @Autowired
    private RuleService repo;

    /**
     * 新增 Rule
     */
    @Operation(summary = "新增规则")
    @PostMapping
    public HttpResult<String> createRule(@RequestBody @Validated Rule rule) {
        repo.createRule(rule);
        return new HttpResult<>("success", true, 200, "规则创建成功");
    }

    /**
     * 根据 Rule 实体条件查询（动态查询）
     */
    @Operation(summary = "根据实体条件查询规则")
    @PostMapping("/search")
    public HttpResult<PageResponse<RuleRes>> searchRules(@RequestBody RuleReq ruleReq) {
        return new HttpResult<>("success", true, 200, repo.searchRules(ruleReq));
    }


    /**
     * 根据 ID 查询单个 Rule
     */
    @Operation(summary = "根据ID查询规则")
    @GetMapping("/{id}")
    public HttpResult<RuleRes> getRuleById(@PathVariable Integer id) {
        return new HttpResult<>(null, true, 200,  repo.getRuleById(id));
    }

    /**
     * 根据 ID 更新 Rule
     */
    @Operation(summary = "根据ID更新规则")
    @PutMapping()
    public HttpResult<String> updateRule( @RequestBody Rule rule) {
        repo.updateRule(rule);
        return new HttpResult<>("success", true, 200, "规则更新成功");
    }

    /**
     * 根据 ID 删除 Rule
     */
    @Operation(summary = "根据ID删除规则")
    @DeleteMapping("/{id}")
    public HttpResult<String> deleteRule(@PathVariable Integer id) {
        repo.deleteRule(id);
        return new HttpResult<>("success", true, 200, "规则删除成功");
    }

    /**
     *执行规则
     */
    @Operation(summary = "执行规则")
    @PutMapping("execute")
    public HttpResult<Object> execute( @RequestBody RuleExecuteRequest ruleExecuteRequest) {
        repo.execute(ruleExecuteRequest);
        return new HttpResult<>("success", true, 200,  repo.execute(ruleExecuteRequest));
    }

}
